package com.siwei.mes.sync.erp.service.impl;

import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.config.UidUtils;
import com.siwei.mes.entity.ShxhSynchronizedata;
import com.siwei.mes.entity.erp.Itemorder;
import com.siwei.mes.entity.erp.Rwdextra;
import com.siwei.mes.entity.erp.RwdextraExtend;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.ExperimentGenConfig;
import com.siwei.mes.entity.experiment.ExperimentSampleSmoke;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.enums.*;
import com.siwei.mes.mapper.ShxhSynchronizedataMapper;
import com.siwei.mes.mapper.erp.RwdextraExtendMapper;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.experiment.ExperimentGenConfigMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.experiment.ExperimentSampleSmokeMapper;
import com.siwei.mes.service.experiment.ExperimentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生成混凝土性能报告
 *
 * @Description: 生成混凝土性能报告
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/11 21:48
 */
@Service
public class GenXnbgExperimentService extends GenAbstractService {
    private static final Logger log = LoggerFactory.getLogger("erp");

    @Resource
    private ExperimentGenConfigMapper experimentGenConfigMapper;
    @Resource
    private ExperimentService experimentService;
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private ExperimentSampleSmokeMapper experimentSampleSmokeMapper;
    @Resource
    private RwdextraExtendMapper rwdextraExtendMapper;
    @Resource
    private ShxhSynchronizedataMapper shxhSynchronizedataMapper;

    /**
     * 获取所有综合性能报告相关的试验项目
     *
     * @return
     */
    public List<String> getZhxnbgTestProjectCodeList() {
        return Arrays.asList(
                TestProjectEnum.CONCRETE_PARAM_XNBG_TLD.getCode(),
                TestProjectEnum.CONCRETE_PARAM_XNBG_HQL.getCode(),
                TestProjectEnum.CONCRETE_PARAM_XNBG_CNSJ.getCode(),
                TestProjectEnum.CONCRETE_PARAM_XNBG_ZNSJ.getCode(),
                TestProjectEnum.CONCRETE_PARAM_XNBG_LLZHL.getCode(),
                TestProjectEnum.CONCRETE_PARAM_XNBG_MSL.getCode(),
                TestProjectEnum.CONCRETE_PARAM_XNBG_KZD.getCode()
        );
    }

    /**
     * 生成混凝土综合性能报告  小票进来的时候判断 对应的任务单是否超过阈值  超过就生成一个委托
     * 同一个任务单如果生成了一个综合性能报告委托 就不需要生成
     */
    public Long genExperiment(Rwdextra rwdextra, Itemorder itemorder, Map<String, TestProjectInfo> testProjectInfoMap) {
        try {
            log.info("生成混凝土综合性能报告开始，任务单号：【{}】，小票id；【{}】", rwdextra.getFrwdh(), itemorder.getItid());
            RwdextraExtend rwdextraExtend = rwdextra.getRwdextraExtend();

            Float scQuantity = rwdextra.getScquantity();//ERP任务单的生产方量
            if (scQuantity == null || scQuantity <= 0) {
                log.info("混凝土综合性能报告生成委托对应ERP任务单生产方量为空，暂不生成！任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }
            log.info("生成混凝土综合性能报告，对应任务的生产方量：【{}】", scQuantity);

            Long experimentId = null;
            if (rwdextraExtend.getIsGenXnbg() == 1) {
                log.info("该任务单已经生成综合性能报告了");
                experimentId = rwdextraExtend.getExperimentId();

                /**插入试验台账对应小票数据和试验台账对应ERP任务单记录*/
                super.insertExperimentRelatedRecords(experimentId, itemorder.getItid(), rwdextra.getFrwdh());
                /**修改试验台账的代表数量*/
                super.updateExperimentBehalfNumberByXnbg(experimentId, Double.valueOf(scQuantity));
                log.info("混凝土综合性能报告生成委托，该任务单已生产综合性能报告，任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return experimentId;
            }

            String fPhbNo = rwdextra.getPhbshow();

            ExperimentGenConfig config = experimentGenConfigMapper.selectOne(new ExperimentGenConfig()
                    .setTestCode(TestProjectEnum.ZONG_HE_XING_NENG.getCode()).setExperimentType(MaterialsEnum.CONCRETE.getCode()));

            if (config == null || config.getIsOpen() == null || config.getIsOpen() == 0) {
                log.info("混凝土综合性能报告生成委托规则配置为空或未开启，暂不生成，任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }

            Integer threshold = config.getCombinationPropertyThreshold();//综合性能报告的阈值
            if (threshold == null || threshold <= 0) {
                log.info("混凝土综合性能报告生成委托规则配置阈值不能为空，暂不生成！任务单：【{}】，小票id：【{}】", rwdextra.getFrwdh(), itemorder.getItid());
                return null;
            }

            log.info("开始组装混凝土【综合性能报告】对应试验委托，配合比号：【{}】,生产方量：【{}】，任务单号：【{}】，小票id：：【{}】",
                    fPhbNo, scQuantity, rwdextra.getFrwdh(), itemorder.getItid());

            if (scQuantity >= threshold) {
                log.info("生成方量大于阈值开始生成综合性能报告，任务单号：【{}】，生产方量：【{}】，阈值：【{}】", rwdextra.getFrwdh(), scQuantity, threshold);
                /**委托试验名称*/
                Set<String> entrustExperimentSet = new HashSet<>();
                /**试验项目code集合*/
                Set<String> testProjectCodeList = new HashSet<>();

                /**获取所有试验项目配置*/
                List<TestProjectInfo> testProjectInfoList = new ArrayList<>();

                /**获取所有需要生成综合性能报告的试验项目配置*/
                List<String> zhxnbgTestProjectCodeList = this.getZhxnbgTestProjectCodeList();

                for (String testCode : zhxnbgTestProjectCodeList) {
                    TestProjectInfo testProjectInfo = testProjectInfoMap.get(testCode);
                    if (testProjectInfo == null) {
                        log.info("混凝土综合性能报告对应试验项目配置未配置，暂不生成！试验项目code：【{}】，任务单：【{}】，小票id：【{}】", testCode, rwdextra.getFrwdh(), itemorder.getItid());
                        continue;
                    }
                    testProjectInfoList.add(testProjectInfo);
                    testProjectCodeList.add(testProjectInfo.getTestCode());
                    entrustExperimentSet.add(testProjectInfo.getTestName());
                }

                /**如果当年的没有需要生成新的试验委托数据*/
                String entrustExperiment = null;
                if (!entrustExperimentSet.isEmpty()) {
                    entrustExperiment = entrustExperimentSet.stream().map(String::valueOf).collect(Collectors.joining(","));
                }

                /**新增混凝土试验台账*/
                Experiment experiment = experimentService.getExperimentInfoByItemOrderInfo(itemorder, CheckEnum.BATCH.getCode(), entrustExperiment, testProjectCodeList);
                experiment.setPhb(fPhbNo);

                /**组装物料相关信息*/
                super.payloadMaterialsInfo(itemorder.getTpz(), experiment);

                experiment.setCreateType(CreateTypeEnum.DEFAULT_CHECK.getCode()).setCreateCheckType(CheckTypeEnum.DEFAULT_CHECK.getCode());
                experiment.setIsXnbg(1);

                /** 协会相关信息，通过企业配置信息赋值**/
                String sampleNo = UidUtils.genNoNumberToYearStr(GenerateCodeEnum.KLLZ_SAMPLENO.getCode(), "%06d", "12");
                String consignId = UidUtils.genNoNumberToYearStr(GenerateCodeEnum.KLLZ_CONSIGNID.getCode(), "%06d", "12");
                String xnbgReportId = GenerateCodeEnum.KLLZ_REPORTID.getCode() + DateHelper.getYear() + UidUtils.genNoNumber(GenerateCodeEnum.KLLZ_REPORTID.getCode(), "%05d");

                experiment.setSampleNo(sampleNo);
                experiment.setReportNo(xnbgReportId);
                experiment.setReportDate(new Date());
                experiment.setCreateType(CreateTypeEnum.DEFAULT_CHECK.getCode());


                experimentMapper.insertSelective(experiment);
                experimentId = experiment.getId();


                ShxhSynchronizedata shxhInfo = shxhSynchronizedataMapper.selectByExperimentIdOne(experimentId);
                if (shxhInfo == null) {
                    //新增对应关系
                    ShxhSynchronizedata synchronizedata = new ShxhSynchronizedata().setSampleId(sampleNo)
                            .setSampleNo(sampleNo).setConsignId(consignId).setExperimentId(experimentId);
                    shxhSynchronizedataMapper.insertSelective(synchronizedata);
                } else {
                    shxhInfo.setSampleId(sampleNo)
                            .setSampleNo(sampleNo).setConsignId(consignId).setExperimentId(experimentId);
                    shxhSynchronizedataMapper.updateByPrimaryKeySelective(shxhInfo);
                }


                if (!testProjectCodeList.isEmpty()) {
                    List<ExperimentDetail> detailList = new ArrayList<>();
                    /**查询所有试验项目信息*/
                    for (TestProjectInfo testProjectInfo : testProjectInfoList) {
                        ExperimentDetail detail = new ExperimentDetail();
                        detail.setExperimentId(experiment.getId());
                        detail.setCheckType(CheckEnum.BATCH.getCode());
                        detail.erpInit(true);
                        detail.setTestProjectCode(testProjectInfo.getTestCode());
                        detail.setTestProjectName(testProjectInfo.getTestName());
                        detail.setObjJson(testProjectInfo.getObjJson());
                        detailList.add(detail);
                    }
                    if (!detailList.isEmpty()) {
                        /**生成对应试验台账详情信息*/
                        experimentDetailMapper.insertList(detailList);
                    }

                    /**新增试验台账抽样*/
                    List<ExperimentSampleSmoke> smokeList = new ArrayList<>();
                    for (TestProjectInfo projectInfo : testProjectInfoList) {
                        /**这里一个试验项目一条记录*/
                        ExperimentSampleSmoke sampleSmoke = new ExperimentSampleSmoke();
                        sampleSmoke.setId(null);
                        sampleSmoke.erpInit(true);
                        sampleSmoke.setExperimentId(experiment.getId());
                        sampleSmoke.setSampleTime(new Date());
                        sampleSmoke.setIsTestBlock(0);// 是否是试块 1-是 0-不是
                        sampleSmoke.setSamplePersonName(experiment.getEntrustPersonName());
                        sampleSmoke.setDisposerPersonName(experiment.getEntrustPersonName());
                        sampleSmoke.setTestProjectCode(projectInfo.getTestCode());
                        sampleSmoke.setTestProjectName(projectInfo.getTestName());
                        sampleSmoke.setSampleUse(projectInfo.getTestName());
                        smokeList.add(sampleSmoke);
                    }

                    if (!smokeList.isEmpty()) {
                        experimentSampleSmokeMapper.insertList(smokeList);
                    }
                }
                /**插入试验台账对应小票数据和试验台账对应ERP任务单记录*/
                super.insertExperimentRelatedRecords(experimentId, itemorder.getItid(), rwdextra.getFrwdh());
                /**修改试验台账的代表数量*/
                super.updateExperimentBehalfNumberByXnbg(experimentId, Double.valueOf(scQuantity));

                /**修改品控扩展记录表*/
                rwdextraExtend.setIsGenXnbg(1).setExperimentId(experimentId);
                rwdextraExtendMapper.updateByPrimaryKeySelective(rwdextraExtend);
                log.info("生成混凝土综合性能报告完成！对应试验委托id：【{}】", experimentId);
                return experimentId;
            }
        } catch (Exception e) {
            super.handleException("混凝土生成综合性能报告失败", e);
            return null;
        }
        log.info("生成混凝土综合性能报告结束");
        return null;
    }
}
